<template>
  <div class="right-card">
    <button class="enter-interview-btn" @click="goto">
      <i class="fa fa-play"></i> 进入面试
    </button>
    <div class="fancy-card knowledge-card">
      <div class="card-header">
        <svg class="icon-knowledge" aria-hidden="true"><use xlink:href="#icon-zhishiku"></use></svg>
        <span>知识卡片</span>
      </div>
      <div class="card-content">
        <p class="question"><span class="qa-label q-label">Q</span><span class="tip-content">{{ currentQuestion.question }}</span></p>
        <p class="answer"><span class="qa-label a-label">A</span><span class="tip-content">{{ currentQuestion.answer }}</span></p>
        <div class="card-footer">
          <span class="card-tag">{{ currentQuestion.field || '通用' }}</span>
        </div>
      </div>
    </div>
    <div class="fancy-card interview-tips">
      <div class="card-header">
        <svg class="icon-tips" aria-hidden="true"><use xlink:href="#icon-tips"></use></svg>
        <span>面试小贴士</span>
      </div>
      <div v-if="loadingTip" class="loading-tip">生成小贴士中...</div>
      <p v-else class="tip-content"> {{ tipContent }}</p>
      <div class="tips-footer">
        <button class="share-btn" @click="generateTip" :disabled="loadingTip">
          <i class="fa fa-refresh"></i> 换一条
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import CryptoJS from 'crypto-js';
import request from '@/utils/request';

export default {
  name: 'RightCard',
  data() {
    return {
      loadingTip: false,
      tipContent: '',
      totalRes: '',
      httpUrl: new URL("https://spark-api.xf-yun.com/v3.5/chat"),
      modelDomain: 'generalv3.5',
      ttsWS: null,
      appId: 'e9f15e7b',
      apiSecret: 'YTk4MzhhOGY5MDNjNWI2ZjAzYjEwMWVi',
      apiKey: '8f4950aa42fdca8eac189b3edb74da82',
      currentQuestion: {
        question: '暂无',
        answer: '',
        field: ''
      },
      knowledgeList: [],
    };
  },
  created() {
    this.fetchKnowledgeData();
    this.generateTip();
  },
  methods: {
    async fetchKnowledgeData() {
      try {
        const response = await request({
          url: '/api/example/Whu_knowledgebase/getList',
          method: 'post',
          data: {
            currentPage: 1,
            pageSize: 100, // 获取足够多的数据供随机选择
            sort: "desc",
            sidx: "todate"
          }
        });

        if (response.data && response.data.list) {
          this.knowledgeList = response.data.list.filter(item => item.tonei === '开');
          this.updateRandomQuestion();
        }
      } catch (error) {
        console.error('获取知识库数据失败:', error);
        this.currentQuestion = {
          question: '数据加载失败',
          answer: '请刷新重试',
          field: '错误'
        };
      }
    },

    updateRandomQuestion() {
      if (this.knowledgeList.length > 0) {
        const randomIndex = Math.floor(Math.random() * this.knowledgeList.length);
        const randomItem = this.knowledgeList[randomIndex];

        this.currentQuestion = {
          question: randomItem.question || '未知问题',
          answer: this.formatAnswer(randomItem.answer),
          field: randomItem.field || '通用'
        };
      }
    },

    formatAnswer(answer) {
      if (!answer) return '暂无答案内容';
      // 简单处理富文本内容，移除HTML标签
      return answer.replace(/<[^>]+>/g, '').substring(0, 150) + '...';
    },
    async generateTip() {
      if (this.loadingTip) return;

      this.loadingTip = true;
      this.tipContent = '';
      this.totalRes = '';

      try {
        const url = await this.getWebsocketUrl();
        this.connectWebSocket(url);
      } catch (error) {
        console.error('生成小贴士失败:', error);
        this.loadingTip = false;
      }
    },
    getWebsocketUrl() {
      return new Promise((resolve) => {
        const host = window.location.host;
        const date = new Date().toGMTString();
        const algorithm = 'hmac-sha256';
        const headers = 'host date request-line';
        const signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${this.httpUrl.pathname} HTTP/1.1`;
        const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.apiSecret);
        const signature = CryptoJS.enc.Base64.stringify(signatureSha);
        const authorizationOrigin = `api_key="${this.apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
        const authorization = btoa(authorizationOrigin);
        const url = `wss://${this.httpUrl.host}${this.httpUrl.pathname}?authorization=${authorization}&date=${date}&host=${host}`;
        resolve(url);
      });
    },
    connectWebSocket(url) {
      if ('WebSocket' in window) {
        this.ttsWS = new WebSocket(url);
      } else {
        this.loadingTip = false;
        alert('浏览器不支持WebSocket');
        return;
      }

      this.ttsWS.onopen = () => {
        this.webSocketSend();
      };

      this.ttsWS.onmessage = (e) => {
        this.handleResult(e.data);
      };

      this.ttsWS.onerror = (e) => {
        console.error('WebSocket错误:', e);
        this.loadingTip = false;
        this.tipContent = '生成小贴士失败，请重试';
      };

      this.ttsWS.onclose = () => {
        this.loadingTip = false;
      };
    },
    webSocketSend() {
      const techTopics = [
        "数据结构", "算法", "设计模式", "系统设计", "数据库",
        "网络协议", "操作系统", "分布式系统", "微服务", "前端框架"
      ];

      const interviewSkills = [
        "技术问题回答", "项目经验描述", "白板编程", "系统架构设计",
        "行为问题回答", "薪资谈判", "面试礼仪", "技术深度展示"
      ];

      const randomCategory = Math.random() > 0.5 ? techTopics : interviewSkills;
      const randomTopic = randomCategory[Math.floor(Math.random() * randomCategory.length)];

      const promptTemplates = [
        `针对${randomTopic}面试，生成一条实用建议`,
        `如何出色地回答关于${randomTopic}的问题？简要说明`,
        `关于${randomTopic}的面试小贴士`,
        `面试中遇到${randomTopic}问题时，应该注意什么？`,
        `分享一个${randomTopic}相关的面试技巧`
      ];

      const randomPrompt = promptTemplates[Math.floor(Math.random() * promptTemplates.length)];

      const params = {
        "header": {
          "app_id": this.appId,
          "uid": "tips-" + Date.now()
        },
        "parameter": {
          "chat": {
            "domain": this.modelDomain,
            "temperature": 0.8,  // 提高温度增加多样性
            "max_tokens": 100
          }
        },
        "payload": {
          "message": {
            "text": [
              {
                "role": "system",
                "content": "你是一个资深技术面试官，擅长给出具体实用的面试建议。回答避免笼统，不要带有*号等格式标记，不大于150字。"
              },
              { "role": "user", "content": randomPrompt }
            ]
          }
        }
      };

      this.ttsWS.send(JSON.stringify(params));
    },
    handleResult(resultData) {
      try {
        const jsonData = JSON.parse(resultData);

        if (jsonData.payload && jsonData.payload.choices && jsonData.payload.choices.text) {
          const content = jsonData.payload.choices.text[0].content;
          this.totalRes += content;

          if (jsonData.header.status === 2) {
            this.tipContent = this.totalRes;
            this.ttsWS.close();
          }
        }
      } catch (error) {
        console.error('解析结果失败:', error);
      }
    },
    goto(){
       this.$router.push({ path: '/scene' });
    }
  },
  beforeDestroy() {
    if (this.ttsWS && this.ttsWS.readyState !== WebSocket.CLOSED) {
      this.ttsWS.close();
    }
  }
};
</script>

<style scoped>
.right-card {
  width: 300px;
  padding: 22px 18px 18px 18px;
  box-sizing: border-box;
  background: rgb(255, 250, 240);
  border-radius: 18px;
  box-shadow: 0 4px 18px 0 rgba(255, 224, 130, 0.10);
  display: flex;
  flex-direction: column;
  align-items: stretch;
}
.enter-interview-btn {
  margin-top: 7%;
  width: 100%;
  padding: 12px 0;
  background: linear-gradient(90deg, #f3e7c9 0%, #e8d7b1 100%);
  color: #a68c5a;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 18px;
  cursor: pointer;
  transition: background 0.18s, color 0.18s, box-shadow 0.18s;
  box-shadow: 0 1px 4px 0 rgba(200, 180, 120, 0.10);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  letter-spacing: 1px;
}
.enter-interview-btn:hover {
  background: linear-gradient(90deg, #e8d7b1 0%, #f3e7c9 100%);
  color: #bfa76a;
  box-shadow: 0 2px 8px 0 rgba(200, 180, 120, 0.16);
}
/* 卡片宽度与右侧整体一致，去除固定高度，内容自适应 */
.fancy-card {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(255, 224, 130, 0.13);
  padding: 26px 18px 20px 18px;
  margin-bottom: 22px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  border: 1px solid #f0e6d2;
  width: 100%;
  min-height: 220px;
  height: auto;
  box-sizing: border-box;
}
.fancy-card:last-child {
  margin-bottom: 0;
}
.card-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 700;
  color: #a67c00;
  margin-bottom: 8px;
  gap: 6px;
}
.icon-knowledge, .icon-tips {
  width: 18px;
  height: 18px;
  color: #ffd54f;
}
.question {
  font-weight: 700;
  margin-bottom: 10px;
  color: #ff9800;
  font-size: 17px;
  letter-spacing: 0.5px;
  display: flex;
  align-items: flex-start;
}
.answer {
  margin-bottom: 10px;
  color: #1976d2;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.2px;
  display: flex;
  align-items: flex-start;
}
.qa-text {
  font-weight: normal;
  color: #552d03;
  font-size: 14px;
  margin-left: 2px;
  letter-spacing: 0;
}
.qa-label {
  display: inline-block;
  min-width: 22px;
  height: 22px;
  line-height: 22px;
  text-align: center;
  font-size: 13px;
  font-weight: bold;
  border-radius: 50%;
  margin-right: 8px;
  color: #fff;
}
.q-label {
  background: linear-gradient(135deg, #ff9800 60%, #ffd54f 100%);
  box-shadow: 0 2px 6px #ffe08244;
}
.a-label {
  background: linear-gradient(135deg, #1976d2 60%, #64b5f6 100%);
  box-shadow: 0 2px 6px #90caf944;
}
.t-label {
  background: linear-gradient(135deg, #43cea2 60%, #185a9d 100%);
  box-shadow: 0 2px 6px #43cea244;
  font-size: 12px;
  border-radius: 8px;
  padding: 0 8px;
  min-width: unset;
  height: 20px;
  line-height: 20px;
  margin-right: 8px;
  letter-spacing: 1px;
}
.tip-content {
  max-height: 250px;
  overflow-y: auto;
  padding-right: 5px;
  margin-bottom: 10px;
  line-height: 1.7;
  color: #1976d2;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: 0.2px;
  display: flex;
  align-items: flex-start;
}
.card-footer {
  display: flex;
  gap: 10px;
}
.card-tag {
  background-color: #fffbe6;
  color: #bfa76a;
  padding: 2px 10px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
}
.interview-tips {
  margin-bottom: 0;
}
.tip-content {
  max-height: 250px;
  overflow-y: auto;
  padding-right: 5px;
  margin-bottom: 10px;
  line-height: 1.6;
  color: #6c757d;
  font-size: 14px;
}
.loading-tip {
  color: #bfa76a;
  font-style: italic;
  padding: 10px 0;
  font-size: 14px;
}
.tips-footer {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
.share-btn {
  background: #fffbe6;
  color: #bfa76a;
  border: none;
  border-radius: 6px;
  padding: 5px 14px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}
.share-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.share-btn:hover:not(:disabled) {
  background: #ffe082;
  color: #fff;
}
</style>
